<template>
  <view class="publish-travel">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <view class="title">发布游记</view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y>
      <view class="form-card">
        <!-- 游记内容编辑区域 -->
        <view class="editor-section">
          <textarea class="content-editor" v-model="content" placeholder="分享你的旅行故事..." :maxlength="2000"
            show-confirm-bar @input="handleContentInput"></textarea>

          <!-- 表情/工具栏 -->
          <view class="editor-toolbar">
            <view class="toolbar-item" @click="showEmojiPicker = !showEmojiPicker">
              <text class="iconfont icon-emoji">😊</text>
            </view>
            <view class="toolbar-item" @click="showLocationPicker">
              <text class="iconfont icon-location">📍</text>
              <text class="toolbar-text">{{ location || '添加位置' }}</text>
            </view>
            <view class="word-count">{{ content.length }}/2000</view>
          </view>

          <!-- 表情选择器 -->
          <view class="emoji-picker" v-if="showEmojiPicker">
            <view class="emoji-list">
              <text v-for="(emoji, index) in emojis" :key="index" class="emoji-item"
                @click="insertEmoji(emoji)">{{ emoji }}</text>
            </view>
          </view>
        </view>

        <!-- 图片上传区域 -->
        <view class="upload-section">
          <view class="section-header">
            <view class="section-title">添加图片</view>
            <view class="section-tips">精美图片让游记更吸引人</view>
          </view>
          <view class="image-area">
            <view class="image-grid">
              <view v-for="(item, index) in imageUrls" :key="index" class="image-preview">
                <image :src="item" mode="aspectFill" @click="previewImage(index)"></image>
                <view class="image-overlay">
                  <view class="delete-btn" @click.stop="deleteImage(index)">
                    <text class="iconfont icon-delete">🗑️</text>
                  </view>
                </view>
              </view>
              <view class="upload-box" @click="chooseImage" v-if="imageUrls.length < 9">
                <text class="iconfont icon-camera"></text>
                <text class="upload-text">添加图片</text>
                <text class="upload-count">{{ imageUrls.length }}/9</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 温馨提示 -->
        <view class="tips-section">
          <text class="tips-icon">💡</text>
          <text class="tips-text">请勿发布违规内容，文明发言</text>
        </view>
      </view>
    </scroll-view>

    <!-- 发布按钮 (移动设备底部固定) -->
    <view class="mobile-publish-btn" @click="handlePublish">
      <text class="btn-text">发布游记</text>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { publishTravel } from '@/api/travel'
import { uploadFile } from '@/api/upload'

// 响应式数据
const imageUrls = ref([]);
const content = ref('')
const location = ref('')
const showEmojiPicker = ref(false)

// 常用表情
const emojis = ref(['😊', '😂', '😍', '🥰', '😎', '🙄', '😮', '😴', '🤔', '👍', '👏', '🙏', '❤️', '🔥', '✨', '🌈', '🌞', '🌙', '⛅', '🌊', '🏞️', '🏔️', '🏝️', '✈️', '🚗', '🚂', '🍕', '🍦', '🍷', '📸', '🎉', '🎊'])

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 选择位置
const showLocationPicker = () => {
  uni.chooseLocation({
    success: (res) => {
      location.value = res.name || res.address
    },
    fail: () => {
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
    }
  })
}

// 插入表情
const insertEmoji = (emoji) => {
  content.value += emoji
}

// 选择图片
const chooseImage = () => {
  const remainCount = 9 - imageUrls.value.length;
  if (remainCount <= 0) {
    uni.showToast({
      title: '最多上传9张图片',
      icon: 'none'
    });
    return;
  }
  
  uni.chooseImage({
    count: remainCount,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      imageUrls.value.push(...res.tempFilePaths);
      showEmojiPicker.value = false;
    }
  });
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    urls: imageUrls.value,
    current: index
  });
};

const deleteImage = (index) => {
  imageUrls.value.splice(index, 1);
};

// 处理内容输入
const handleContentInput = (e) => {
  content.value = e.detail.value
  // 输入时关闭表情选择器
  showEmojiPicker.value = false
}

// 发布游记
const handlePublish = async () => {
  if (!content.value.trim()) {
    uni.showToast({
      title: '请输入游记内容',
      icon: 'none'
    });
    return;
  }

  if (imageUrls.value.length === 0) {
    uni.showToast({
      title: '请上传图片',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: '正在发布...'
    });

    // 上传图片并获取URL
    const uploadPromises = imageUrls.value.map(async (imageUrl) => {
      if (imageUrl) {
        const uploadRes = await uploadFile(imageUrl);
        return uploadRes.data.url;
      }
      return '';
    });

    // 等待所有图片上传完成
    const uploadedImageUrls = await Promise.all(uploadPromises);
    
    // 过滤掉空字符串并拼接成逗号分隔的字符串
    const imageString = uploadedImageUrls.filter(url => url).join(',');

    const res = await publishTravel({
      content: content.value,
      image: imageString, // 修改为 image 字段
      location: location.value,
      userId: uni.getStorageSync('userInfo').id
    });

    if (res.code === 200) {
      uni.hideLoading();
      uni.showToast({
        title: '发布成功',
        icon: 'success'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(res.message || '发布失败');
    }
  } catch (err) {
    uni.hideLoading();
    uni.showToast({
      title: err.message || '发布失败',
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
.publish-travel {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 120rpx; // 为底部发布按钮留出空间

  .nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 90rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    z-index: 100;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);

    .left {
      padding: 15rpx;
      margin-left: -15rpx;

      .iconfont {
        font-size: 36rpx;
        color: #333;
      }
    }

    .title {
      font-size: 34rpx;
      font-weight: 500;
      color: #333;
    }

    .right {
      padding: 15rpx;
      margin-right: -15rpx;

      .publish-btn {
        display: inline-block;
        font-size: 28rpx;
        color: white;
        background-color: #42b983;
        padding: 12rpx 30rpx;
        border-radius: 30rpx;
        font-weight: 500;
      }
    }
  }

  .content {
    margin-top: 90rpx;
    padding: 30rpx;
    height: calc(100vh - 90rpx - 120rpx); // 减去顶部导航和底部按钮的高度
    box-sizing: border-box;

    .form-card {
      background-color: #fff;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
      overflow: hidden;
    }

    .editor-section {
      padding: 30rpx;
      position: relative;
      border-bottom: 1px solid #f0f0f0;

      .content-editor {
        width: 100%;
        min-height: 350rpx;
        font-size: 30rpx;
        line-height: 1.8;
        color: #333;
        box-sizing: border-box;
        padding-bottom: 60rpx;
      }

      .editor-toolbar {
        display: flex;
        align-items: center;
        margin-top: 20rpx;

        .toolbar-item {
          display: flex;
          align-items: center;
          margin-right: 30rpx;
          padding: 10rpx;

          .iconfont {
            font-size: 40rpx;
            color: #666;
            margin-right: 8rpx;
          }

          .toolbar-text {
            font-size: 26rpx;
            color: #666;
            max-width: 200rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .word-count {
          margin-left: auto;
          font-size: 24rpx;
          color: #bbb;
        }
      }

      .emoji-picker {
        margin-top: 20rpx;
        background-color: #f9f9f9;
        border-radius: 12rpx;
        padding: 20rpx;

        .emoji-list {
          display: flex;
          flex-wrap: wrap;

          .emoji-item {
            font-size: 40rpx;
            padding: 10rpx;
            cursor: pointer;
          }
        }
      }
    }

    .upload-section {
      padding: 30rpx;

      .section-header {
        display: flex;
        flex-direction: column;
        margin-bottom: 20rpx;

        .section-title {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .section-tips {
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }

      .image-area {
        width: 100%;
        padding: 20rpx 0;

        .image-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20rpx;
        }

        .upload-box {
          width: 100%;
          height: 220rpx;
          background-color: #f9f9f9;
          border-radius: 12rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border: 1px dashed #ddd;
          transition: all 0.3s;
          box-sizing: border-box;
          position: relative;

          &:active {
            background-color: #f0f0f0;
          }

          .iconfont {
            font-size: 60rpx;
            color: #42b983;
            margin-bottom: 10rpx;
          }

          .upload-text {
            font-size: 24rpx;
            color: #999;
          }

          .upload-count {
            font-size: 22rpx;
            color: #bbb;
            margin-top: 6rpx;
          }
        }

        .image-preview {
          width: 100%;
          height: 220rpx;
          border-radius: 12rpx;
          overflow: hidden;
          position: relative;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

          image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .image-overlay {
            position: absolute;
            top: 0;
            right: 0;
            padding: 10rpx;
            
            .delete-btn {
              width: 44rpx;
              height: 44rpx;
              background-color: rgba(0, 0, 0, 0.5);
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;

              .iconfont {
                font-size: 28rpx;
                color: #fff;
              }
            }
          }
        }
      }
    }

    .tips-section {
      padding: 30rpx;
      display: flex;
      align-items: center;
      border-top: 1px solid #f0f0f0;

      .tips-icon {
        font-size: 32rpx;
        margin-right: 10rpx;
      }

      .tips-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .mobile-publish-btn {
    position: fixed;
    bottom: 30rpx;
    left: 30rpx;
    right: 30rpx;
    height: 90rpx;
    background-color: #42b983;
    border-radius: 45rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 6rpx 20rpx rgba(66, 185, 131, 0.3);
    z-index: 90;

    .btn-text {
      color: white;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
}
</style>
